package com.wk;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.jms.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ActiveMq {


    @Test
    public void test1() throws JMSException {

        //创建连接工厂
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://39.99.195.227:61616");
        //创建连接

        Connection connection = factory.createConnection();
        //创建会话 参数1 要不要开启事务  参数2  签收机制 AUTO_ACKNOWLEDGE 自动签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //通过会话创建目的地,目的地可以是Queue Topic
        Queue queue = session.createQueue("java-mq");

        //创建生产者  参数为:目的地
        MessageProducer producer = session.createProducer(queue);

        //创建一个消息对象,TextMessage
        TextMessage message = session.createTextMessage("第一条消息");

        //生产者发送消息
        producer.send(message);

        //释放资源
        producer.close();
        session.close();
        connection.close();

    }


    @Test
    public void test2() throws JMSException {
        //创建工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("tcp://39.99.195.227:61616");
        //创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        //消费者需要写connection.start
        connection.start();


        //创建session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地
        Queue queue = session.createQueue("java-mq");

        //创建消费者
        MessageConsumer consumer = session.createConsumer(queue);

        //消费信息  receive()返回值是Message
        TextMessage receive = (TextMessage) consumer.receive();
        System.out.println(receive.getText()+"获取到的信息");

        //释放资源
        consumer.close();
        session.close();
        connection.close();



    }

}
